package pl.bristleback.chat.actions;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.jwebsocket.api.WebSocketConnector;
import org.jwebsocket.token.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import pl.bristleback.chat.services.UsersService;
import pl.bristleback.chat.utils.SendMessageSupport;
import pl.bristleback.server.bristle.actions.AnnotatedRemoteAction;
import pl.bristleback.server.bristle.actions.RemoteAction;
import pl.bristleback.server.bristle.utils.BristleTokenFactory;
import pl.bristleback.server.bristle.utils.JsonUtil;

/**
 * //@todo class description
 * <p/>
 * Created on: 14.04.11 16:05 <br/>
 *
 * @author Paweł Machowski
 */
@Controller
@AnnotatedRemoteAction(actionName = "CONNECTION_STOPPED_ACTION_NAME")
public class DisconnectAction implements RemoteAction {
  private static Logger log = Logger.getLogger(DisconnectAction.class.getName());

  @Autowired
  private SendMessageSupport sender;

  @Autowired
  private UsersService usersService;

  @Override
  public void performAction(WebSocketConnector connector, Token token) {

    usersService.removeUserByConnectorId(connector.getId());

    Token sendToken;
    try {
      sendToken = BristleTokenFactory.createJsonToken("listOfUsers", JsonUtil.getJsonArray(usersService.getAllUsers(), true), "users");
      sender.broadcastLogged(sendToken);
    } catch (JSONException e) {
      log.error(e);
    }
  }
}